package cn.appsys.service.impl;

import cn.appsys.pojo.EmailMessage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Super Cui on 2017/10/16.
 */
@Service("emailService")
public class EmailService {
    private JavaMailSender mailSender;
    private Configuration freeMarkerConfiguration;

    private String getMailText(EmailMessage emailMessage){
        String htmlText = "";
        try {
            Template template = freeMarkerConfiguration.getTemplate("mail.ftl");
            Map map = new HashMap();
            map.put("receiverName",emailMessage.getReceiverName());
            map.put("emailCode",emailMessage.getEmailCode());
            map.put("senderName",emailMessage.getSenderName());
            map.put("sendTime",new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date()));
            htmlText = FreeMarkerTemplateUtils.processTemplateIntoString(template,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return htmlText;
    }
    /**
     * 发送信息
     * @param emailMessage
     */
    public void send(EmailMessage emailMessage){
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"UTF-8");
            helper.setFrom(emailMessage.getSenderEmail());
            helper.setTo(emailMessage.getReceiverEmail());
            helper.setSubject(emailMessage.getTitle());
            helper.setText(getMailText(emailMessage));
            mailSender.send(mimeMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public JavaMailSender getMailSender() {
        return mailSender;
    }

    public void setMailSender(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    public Configuration getFreeMarkerConfiguration() {
        return freeMarkerConfiguration;
    }

    public void setFreeMarkerConfiguration(Configuration freeMarkerConfiguration) {
        this.freeMarkerConfiguration = freeMarkerConfiguration;
    }
}
